//
//  BIBFullChartComponent.m
//  XYLib
//
//  Created by blts on 2018/5/7.
//  Copyright © 2018年 XYLib. All rights reserved.
//

#import "BIBFullChartComponent.h"
#import "WXUtility.h"
#import "BIBKLineCandleView.h"
#import "BIBChartPriceView.h"
#import "BIBIndexTypeView.h"
#import "BIBMACDLineView.h"
#import "BIBRSILineView.h"
#import "BIBKDJLineView.h"
#import "BIBBOLLLineView.h"
#import "BIBMALineView.h"
#import "BIBOSMALineView.h"
#import "Masonry.h"
#import "BIBKLineCandleModel.h"
#import "NSString+Extension.h"

#define IPHONE_WIDTH [UIScreen mainScreen].bounds.size.width
#define SizeScaleW (IPHONE_WIDTH/375)  //屏幕宽的缩放比例

#define IPHONE_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SizeScaleH (IPHONE_HEIGHT/667)  //屏幕高的缩放比例

#define SizeScale_Height (SizeScaleW == 1 ? 1 : IPHONE_HEIGHT/667)  //屏幕高的缩放比例(iphone X屏幕宽的缩放比例为1时，高的缩放比例也为1，不随SizeScaleH的改变而改变）


#define TimeLayerHeight 22 //指标图底部时间和日期区域的高度
#define ScreenCandleNumber 80 //蜡烛图的个数

#define UpColor (@"30b700")
#define DownColor (@"eb403e")
#define CurrentColor (@"2e74e9")
#define CurrentLineColor (@"2e74e9")
#define TimeColor (@"242e3b")
#define FormatYLabel 2
#define MarginRight 2

@interface BIBFullChartComponent()<BIBKLineCandleViewProtocol>

@property(nonatomic,strong)UIView *view_bg;//主背景view

@property(nonatomic,strong)UIScrollView *scrollView_quoteChart;//
@property(nonatomic,strong)BIBKLineCandleView *view_candleChart;//蜡烛图的主view
@property(nonatomic,strong)UIView *view_box_candle;//蜡烛图的覆盖层
@property(nonatomic,strong)BIBChartPriceView *view_price_candle;//蜡烛图的右侧价格

@property (nonatomic,strong) NSMutableArray *dataSource;//k线的数据集
@property (nonatomic,assign) NSInteger kLineType;//k线图的分类
@property (nonatomic,assign) BOOL isRightMove;//是否右滑加载更多历史数据

@property (nonatomic,strong) UIView *currentView;//实时线
@property (nonatomic,strong) UILabel *label_current;//实时报价
@property (nonatomic,strong) NSString* currentLineColor;//实时线颜色值
@property (nonatomic,assign) NSString* currentQuote;//当前报价
@property (nonatomic,assign) int formatYLabel;//y轴位数
@property (nonatomic,strong) NSString* currentColor;//当前报价色值
@property (nonatomic,copy) NSString* dropColor;//下跌颜色
@property (nonatomic,copy) NSString* riseColor;//上涨颜色
@property (nonatomic,copy) NSString* timeColor;// 时间轴颜色
@property (nonatomic,assign) NSInteger screenCandleNumber;//每屏蜡烛图的个数
@property (nonatomic, assign) CGFloat marginRight; // 蜡烛图右边距
@end

@implementation BIBFullChartComponent

WX_EXPORT_METHOD(@selector(setFullScreen:)); // 暴露该方法给js
WX_EXPORT_METHOD(@selector(rotationLive)); // 暴露该方法给js
WX_EXPORT_METHOD(@selector(setloadMoreData:)); // 暴露该方法给js
WX_EXPORT_METHOD(@selector(setQuoteData:)); // 暴露该方法给js

- (instancetype)initWithRef:(NSString *)ref type:(NSString *)type styles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance *)weexInstance
{
    if (self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance])
    {
        // handle your attributes
        // handle your styles
        _kLineType = 0;
        _isRightMove = NO;
        self.currentLineColor = attributes[@"currentLineColor"] ? [WXConvert NSString:attributes[@"currentLineColor"]] : CurrentLineColor;
        self.riseColor = attributes[@"riseColor"] ? [WXConvert NSString:attributes[@"riseColor"]] : UpColor;
        self.dropColor = attributes[@"dropColor"] ? [WXConvert NSString:attributes[@"dropColor"]] : DownColor;
        self.currentColor = attributes[@"currentColor"] ? [WXConvert NSString:attributes[@"currentColor"]] : CurrentColor;
        self.screenCandleNumber = attributes[@"CandleNumber"] ?  [attributes[@"CandleNumber"] integerValue]:ScreenCandleNumber;
        self.formatYLabel = attributes[@"formatYLabel"] ? [attributes[@"formatYLabel"] intValue]:FormatYLabel;
        self.timeColor = attributes[@"xLabelColor"] ? [WXConvert NSString:attributes[@"xLabelColor"]] : TimeColor;
        self.marginRight = attributes[@"marginRight"] ? [WXConvert CGFloat:attributes[@"marginRight"]] : MarginRight;
    }
    return self;
}

-(void)setFullScreen:(NSString *)str
{
    _kLineType = [str integerValue];
}

-(void)rotationLive{
    
}
-(void)setQuoteData:(NSArray*)quoteData{
    if (quoteData == nil || quoteData == NULL) {
        return;
    }
    if (self.dataSource && self.dataSource.count>0) {
        if (_isRightMove) {
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.dataSource];
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:quoteData];
            [self.dataSource addObjectsFromArray:arr];
        }else {
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:quoteData];
        }
    }else if (self.dataSource && self.dataSource.count<=0){
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:quoteData];
    }
    
    [self loadData:_isRightMove];
}

-(void)setloadMoreData:(NSArray *)array{
    if (array && self.dataSource) {
        [self.dataSource addObjectsFromArray:array];
        [self loadData:_isRightMove];
    }
}
- (void)updateAttributes:(NSDictionary *)attributes
{
    if (attributes[@"typeChannelIndex"]) {
        _kLineType = [attributes[@"typeChannelIndex"] integerValue];
        _isRightMove = NO;
    }
    if (attributes[@"quoteData"]) {
        NSArray *array = attributes[@"quoteData"];
        if (self.dataSource && self.dataSource.count>0) {
            if (_isRightMove) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.dataSource];
                [self.dataSource removeAllObjects];
                [self.dataSource addObjectsFromArray:array];
                [self.dataSource addObjectsFromArray:arr];
            }else {
                [self.dataSource removeAllObjects];
                [self.dataSource addObjectsFromArray:array];
            }
        }else if (self.dataSource && self.dataSource.count<=0){
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:array];
        }
        
        [self loadData:_isRightMove];
    }
    if (attributes[@"formatYLabel"]) {
        self.formatYLabel = [attributes[@"formatYLabel"] intValue];
    }
    if (attributes[@"socketBid"]) {
        self.currentQuote = attributes[@"socketBid"];
        [self showQuoteLine];
    }else if (attributes[@"socketLine"]) {
        self.currentQuote = attributes[@"socketBid"];
        [self showQuoteLine];
    }
}
//处理k线数据
-(void)loadData:(BOOL)isReload
{
    NSMutableArray *arr_model = [NSMutableArray array];
    for (int i = 0; i < self.dataSource.count; i++) {
        BIBKLineCandleModel *model = [[BIBKLineCandleModel alloc] init];
        NSMutableDictionary *dic = self.dataSource[i];
        model.open = [[dic objectForKey:@"Open"] floatValue];
        model.high = [[dic objectForKey:@"High"] floatValue];
        model.low =  [[dic objectForKey:@"Low"] floatValue];
        model.close = [[dic objectForKey:@"Close"] floatValue];
        model.date = [dic objectForKey:@"DateTime"];
        if (![NSString isBlankString:model.date]) {
            model.date = [self solveTheDateString:model.date];
            if (_kLineType == 1 || _kLineType == 2 || _kLineType == 3) {
                model.date = [NSString getTheDateStringByTimeStamp:model.date withFormat:@"YYYY-MM-dd"];
            }else{
                model.date = [NSString getTheDateStringByTimeStamp:model.date withFormat:@"MM-dd HH:mm"];
            }
        }
        [arr_model addObject:model];
    }
    if (arr_model && arr_model.count > 0) {
        [self reloadData:arr_model reload:isReload];
    }
}
- (void)reloadData:(NSMutableArray*)array reload:(BOOL)reload
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        for (NSInteger i = 0;i<array.count;i++)
        {
            BIBKLineCandleModel *model = array[i];
            //设置多少个点画一条竖线（时间线）根据显示的K线个数displayCount和时间线的比值
            self.view_candleChart.displayCount = self.screenCandleNumber > self.dataSource.count ? self.dataSource.count : self.screenCandleNumber;
            NSInteger num = self.view_candleChart.displayCount/5;
            num = num < 1 ? 2 : num;
            if (i % num == 0){
                model.isDrawDate = YES;
            }
            else
            {
                model.isDrawDate = NO;
            }
        }
        self.view_candleChart.dataArray = array;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload){
                [self.view_candleChart reload];
            }
            else
            {
                [self.view_candleChart stockFill];
            }
        });
    });
}

//处理特殊时间值 /Date(1233243523+0800)/
-(NSString *)solveTheDateString:(NSString *)date
{
    date = [date stringByReplacingOccurrencesOfString:@"/" withString:@""];
    date = [date stringByReplacingOccurrencesOfString:@"Date(" withString:@""];
    date = [date stringByReplacingOccurrencesOfString:@")" withString:@""];
    if ([date hasSuffix:@"+0800"]) {
        date = [date stringByReplacingOccurrencesOfString:@"+0800" withString:@""];
    }
    if ([date hasSuffix:@"-0000"]) {
        date = [date stringByReplacingOccurrencesOfString:@"-0000" withString:@""];
    }
    return date;
}

- (UIView *)loadView {
    _view_bg = [[UIView alloc] init];
    return _view_bg;
}
-(void)viewDidLoad
{
    [self.view addSubview:self.scrollView_quoteChart];
    [self.scrollView_quoteChart addSubview:self.view_candleChart];
    [self.view addSubview:self.view_box_candle];
    [self.view_box_candle addSubview:self.view_price_candle];
    [self.view_box_candle addSubview:self.currentView];//实时线
    [self.view_box_candle addSubview:self.label_current];//实时报价
    [self setLayout];
}


-(void)setLayout
{
    [_scrollView_quoteChart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(5);
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-18);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    [_view_candleChart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView_quoteChart.mas_top).offset(0);
        make.left.equalTo(self.scrollView_quoteChart.mas_left).offset(0);
        make.right.equalTo(self.scrollView_quoteChart.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(-TimeLayerHeight);
    }];
    [_view_box_candle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view_candleChart.mas_top).offset(0);
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-TimeLayerHeight);
    }];
    [_view_price_candle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view_box_candle.mas_top).offset(0);
        make.right.equalTo(self.view_box_candle.mas_right).offset(0);
        make.width.equalTo(@(80));
        make.bottom.equalTo(self.view_box_candle.mas_bottom).offset(0);
    }];
    
    [_label_current mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view_box_candle.mas_right).offset(-2);
    }];
    
    [_currentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view_box_candle.mas_left).offset(0);
        make.right.equalTo(self.label_current.mas_left).offset(0);
        make.height.equalTo(@(1));
    }];
}

-(void)showQuoteLine
{
//    if (self.currentQuote>10) {
//        self.label_current.text = [NSString stringWithFormat:@"%.02f",self.currentQuote];
//    }else{
//        self.label_current.text = [NSString stringWithFormat:@"%.04f",self.currentQuote];
//    }
    
    self.label_current.text = self.currentQuote;
    if (self.view_candleChart.maxY <= 0 || self.view_candleChart.minY<=0 || self.view_candleChart.minY >= self.view_candleChart.maxY) {
        return;
    }
    
    float scaleY = (self.view_candleChart.maxY - [self.currentQuote floatValue])/(self.view_candleChart.maxY-self.view_candleChart.minY);
    if (scaleY<=0) {
        scaleY = 0;
    }else if(scaleY>=1){
        scaleY = 1;
    }
    CGFloat yPositoin = CGRectGetHeight(self.view_box_candle.bounds)*scaleY;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentView.centerY = yPositoin;
        self.label_current.centerY = yPositoin;
    });
}

#pragma mark IGoldCandleChartViewProtocol  蜡烛图的代理  Method

- (void)displayLastModel:(BIBKLineCandleModel *)kLineModel
{
    //取当前屏幕最后一根k线model  数据显示在顶部view
    //    _view_top.model = kLineModel;
}
- (void)longPressCandleViewWithIndex:(NSInteger)kLineModeIndex kLineModel:(BIBKLineCandleModel *)kLineModel
{
    //长按手势 取长按的那根k线model  数据显示在顶部view
    //    _view_top.model = kLineModel;
}
- (void)displayScreenleftPostion:(CGFloat)leftPostion startIndex:(NSInteger)index count:(NSInteger)count
{
    [self showIndexLineView:leftPostion startIndex:index count:count];
}
- (void)showIndexLineView:(CGFloat)leftPostion startIndex:(NSInteger)index count:(NSInteger)count
{
    //k线图右侧的price数据
    CGFloat max_y = self.view_candleChart.maxY;
    CGFloat min_y = self.view_candleChart.minY;
    NSString* format = [NSString stringWithFormat:@"%%.%df", self.formatYLabel];
    _view_price_candle.maxPriceLabel.text = [NSString stringWithFormat:format,max_y];
    _view_price_candle.smallMaxPriceLabel.text = [NSString stringWithFormat:format,(max_y-min_y)*3/4+min_y];
    _view_price_candle.middlePriceLabel.text = [NSString stringWithFormat:format,(max_y - min_y)/2 + min_y];
    _view_price_candle.bigMinPriceLabel.text = [NSString stringWithFormat:format,(max_y - min_y)/4 + min_y];
    _view_price_candle.minPriceLabel.text = [NSString stringWithFormat:format,min_y];
    [self showQuoteLine]; //显示实时线的位置
}

//k线图右滑加载更多数据
-(void)displayMoreData:(BOOL)isRightMove
{
    _isRightMove = isRightMove;
    [self.weexInstance fireGlobalEvent:@"ScrollKlineChart" params:@{@"isRight":[NSNumber numberWithBool:isRightMove]}];
}

#pragma mark Private Methods
//得到当前自身的高度
- (CGFloat)getSelfHeight {
    return self.view.frame.size.height;
}
//得到当前自身的宽度
- (CGFloat)getSelfWidth {
    return self.view.frame.size.width;
}

-(UIScrollView *)scrollView_quoteChart
{
    if (!_scrollView_quoteChart) {
        _scrollView_quoteChart = [UIScrollView new];
        _scrollView_quoteChart.scrollEnabled = YES;
        _scrollView_quoteChart.bounces = YES;
        _scrollView_quoteChart.alwaysBounceHorizontal = YES;
        _scrollView_quoteChart.showsHorizontalScrollIndicator = NO;
        _scrollView_quoteChart.backgroundColor = [UIColor whiteColor];
    }
    return _scrollView_quoteChart;
}

-(BIBKLineCandleView *)view_candleChart
{
    if (!_view_candleChart) {
        _view_candleChart = [BIBKLineCandleView new];
        _view_candleChart.delegate = self;
        _view_candleChart.candleSpace = 2;//蜡烛图的间距(蜡烛图的宽度动态计算)
        _view_candleChart.displayCount = self.screenCandleNumber;//蜡烛图的个数
        _view_candleChart.lineWidth = 0.5*SizeScaleW;//蜡烛图中线的宽
        _view_candleChart.leftMargin = 2;
        _view_candleChart.rightMargin = self.marginRight; // 右间距
        _view_candleChart.topMargin = 17;
        _view_candleChart.bottomMargin = 17;
        _view_candleChart.minHeight = 0.5;
        _view_candleChart.timeLayerHeight = TimeLayerHeight;
        _view_candleChart.riseColor = self.riseColor;
        _view_candleChart.dropColor = self.dropColor;
        _view_candleChart.timeColor = self.timeColor;
    }
    return _view_candleChart;
}
-(UIView *)view_box_candle
{
    if (!_view_box_candle) {
        _view_box_candle = [UIView new];
        _view_box_candle.userInteractionEnabled = NO;
        _view_box_candle.layer.borderWidth = 0.5*SizeScaleW;
        _view_box_candle.layer.borderColor = [UIColor colorWithStr:@"e5e5e5"].CGColor;
    }
    return _view_box_candle;
}
-(BIBChartPriceView *)view_price_candle
{
    if (!_view_price_candle) {
        _view_price_candle = [BIBChartPriceView new];
        _view_price_candle.textColor = [UIColor colorWithStr:@"9ba1ab"];
        _view_price_candle.textFont = [UIFont systemFontOfSize:12.0];
    }
    return _view_price_candle;
}
-(UIView *)currentView{
    if (!_currentView) {
        _currentView = [[UIView alloc] init];
        //[UIColor colorWithStr:@"518deb"];
//        _currentView.backgroundColor = [UIColor colorWithStr:@"518deb"];
        _currentView.backgroundColor = [UIColor colorWithStr:self.currentLineColor];
    }
    return _currentView;
}
-(UILabel *)label_current{
    if (!_label_current) {
        _label_current = [[UILabel alloc] init];
        _label_current.textAlignment = NSTextAlignmentRight;
        _label_current.textColor = [UIColor colorWithStr:self.currentColor];
        _label_current.font = [UIFont boldSystemFontOfSize:12.0];
        _label_current.text = @"";
        _label_current.backgroundColor = [UIColor clearColor];
    }
    return _label_current;
}

-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}
@end
